package com.luyuan.crm.member.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.model.DataModel;

import org.hibernate.criterion.Order;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.user.service.UserMemberService;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.web.jsf.context.TableContext;
import com.ruijie.web.jsf.model.PageDataModel;
import com.ruijie.web.jsf.model.TableOrder;
import com.ruijie.web.jsf.model.TablePage;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.query.criteria.RestrictionTemplate;

@Component("memberUserAction")
@Scope("view")
public class MemberUserAction extends BaseAction {

    // 查询条件
    private AppUser criteria = new AppUser();

    public AppUser getCriteria() {
        return criteria;
    }

    public void setCriteria(AppUser criteria) {
        this.criteria = criteria;
    }

    // 添加或编辑模型
    private AppUser appUser;

    public AppUser getAppUser() {
        String userId = this.getRequestParameter("memberId");
        if (userId != null && !"".equals(userId)) {
            appUser = appUserService.getById(userId);
        }
        if (appUser == null) {
            appUser = new AppUser();
        }
        return appUser;
    }

    public void setAppUser(AppUser appUser) {
        this.appUser = appUser;
    }

    @Resource(name = "userMemberService")
    private UserMemberService appUserService;

    public DataModel getTableModel() {
        TablePage limit = TableContext.getTablePage();
        List<TableOrder> tableOrders = TableContext.getTableOrders();
        List<Order> orders = new ArrayList<Order>();
        for (TableOrder order : tableOrders) {
            if (order.toOrder() == null) {
                continue;
            }
            orders.add(order.toOrder());
        }
        CriteriaTemplate c = CriteriaTemplate.forClass(AppUser.class);
        RestrictionTemplate r = new RestrictionTemplate(true);
        c.add(r.like("userName", criteria.getUsername()));
        c.add(r.in("会员", criteria.getRoles()));
        Page page = appUserService.pagedQuery(c, limit.getPage(), limit.getPageSize(), orders);
        return new PageDataModel(page);
    }

    public void updatePassword() {
        appUserService.updatePassword(appUser.getUsername(), appUser.getPassword());

        addGlobalI18nMessage("密码修改成功！");
    }
}
